package cn.taroco.common.web.resolver;

import cn.taroco.common.constants.SecurityConstants;
import cn.taroco.common.vo.LoginUser;
import cn.taroco.common.vo.SysRole;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Token转化LoginUser
 *
 * @author liuht
 * @date 2017/12/21
 */
@Slf4j
public class TokenArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 1. 入参筛选
     *
     * @param methodParameter 参数集合
     * @return 格式化后的参数
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().equals(LoginUser.class);
    }

    /**
     * 入参处理
     *
     * @param methodParameter       入参集合
     * @param modelAndViewContainer model 和 view
     * @param nativeWebRequest      web相关
     * @param webDataBinderFactory  入参解析
     * @return 包装对象
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String username = request.getHeader(SecurityConstants.USER_HEADER);
        String roles = request.getHeader(SecurityConstants.USER_ROLE_HEADER);
        log.info("resolveArgument username :{} roles:{}", username, roles);
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        List<SysRole> sysRoleList = new ArrayList<>();
        if (StringUtils.isNotEmpty(roles)) {
            Arrays.stream(roles.split(",")).forEach(role -> {
                SysRole sysRole = new SysRole();
                sysRole.setRoleName(role);
                sysRoleList.add(sysRole);
            });
            loginUser.setRoleList(sysRoleList);
        }
        return loginUser;
    }

}
